package com.wolfking.converter.transform.base;


import com.google.common.collect.Sets;
import com.wolfking.converter.transform.FieldTransform;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.Set;

@Slf4j
public class StringFieldTransform implements FieldTransform<String> {

    private final Set<Class<?>> classes = Sets.newHashSet(String.class);

    @Override
    public boolean canTransform(Class<?> fieldType) {
        return classes.contains(fieldType);
    }

    @Override
    public String transform(Object value) {
        String stringValue = null;

        if (value instanceof String) {
            stringValue = (String) value;
        } else if (value instanceof byte[]) {
            stringValue = new String((byte[]) value);
        } else if (value instanceof Byte[]) {
            Byte[] value1 = (Byte[]) value;
            byte[] bytes = new byte[value1.length];
            System.arraycopy(value1, 0, bytes, 0, bytes.length);
            stringValue = new String(bytes);
        } else if (value instanceof InputStream) {
            InputStream inputStream = (InputStream) value;
            byte[] buffer = new byte[2048];
            int readBytes;
            StringBuilder sb = new StringBuilder();
            try {
                while ((readBytes = inputStream.read(buffer)) > 0) {
                    sb.append(new String(buffer, 0, readBytes));
                }
                stringValue = sb.toString();
            } catch (Exception e) {
                log.warn("", e);
            } finally {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    log.debug("", e);
                }
            }
        }

        if (stringValue != null) {
            return stringValue;
        } else {
            return value.toString();
        }
    }
}
